package com.cloud.school.bus.teacherhelper.modules.information;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.android.support.jhf.androidpulltorefresh.library.ILoadingLayout;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshListView;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.Mode;
import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.IErrorListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.popupwindow.CustomPopupWindow;
import com.android.support.jhf.utils.ClipboardUtils;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.InputMethodUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseAboveFragment;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic.OnGetPicSucceed;
import com.cloud.school.bus.teacherhelper.base.utils.PictureUtil;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Letter;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.modules.HomeMenuFragment;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.BigPictureActivity;
import com.cloud.school.bus.teacherhelper.modules.information.adapter.InformationAdapter;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;
import com.cloud.school.bus.teacherhelper.protocol.privateletter.GetPrivateLetterListRequest;
import com.cloud.school.bus.teacherhelper.protocol.privateletter.GetPrivateLetterListResponse;
import com.cloud.school.bus.teacherhelper.protocol.privateletter.SendPrivateLetterRequest;
import com.cloud.school.bus.teacherhelper.protocol.privateletter.SendPrivateLetterResponse;

/**
 * 系统消息
 * 
 * @author lenovo
 * 
 */
public class InformationFragment extends BaseAboveFragment {

	/** 更新列表通知 */
	public static final String UPDATE_INFOR_LIST = "update_infor_list";

	private PullToRefreshListView mPullToRefreshListView;
	private InformationAdapter mInformationAdapter;
	private ViewGroup mNoDataLayout;

	private UploadPic mUploadPic;
	private EditText mContentEditText;

	private List<Letter> mLetterList = new ArrayList<Letter>();
	private String mLastStartTime = "0";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_information, null);
		setViewData(view);
		return view;
	}

	@Override
	protected void setViewData(View view) {

		mUploadPic = new UploadPic(mFragment);

		mPullToRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.listView);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
		ILoadingLayout iLoadingLayout = mPullToRefreshListView
				.getLoadingLayoutProxy();
		iLoadingLayout.setPullLabel(getString(R.string.pull_down_more));
		iLoadingLayout
				.setRefreshingLabel(getString(R.string.release_loading_more));
		iLoadingLayout
				.setReleaseLabel(getString(R.string.release_loading_more));
		ListView listView = mPullToRefreshListView.getRefreshableView();
		listView.setSelector(getResources().getDrawable(
				android.R.color.transparent));
		listView.setDivider(getResources().getDrawable(
				android.R.color.transparent));
		listView.setDividerHeight(10);
		mInformationAdapter = new InformationAdapter(mParentContext,
				mLetterList);
		mPullToRefreshListView.setAdapter(mInformationAdapter);

		mContentEditText = (EditText) view.findViewById(R.id.contentEditText);
		
		mNoDataLayout = (ViewGroup)view.findViewById(R.id.noDataLayout);

		getPrivateLetterList(false);

		setTitleNavBar(view);
		setListener(view);

	}

	/**
	 * 发送私信
	 * 
	 * @param picPathString
	 *            不为null表示发送照片
	 * @param contentString
	 *            不为null表示发送字符串
	 * @param requestCode
	 *            调用系统照相机返回或者是系统相册返回
	 */
	private void sendPrivateLetter(final String picPathString,
			String contentString, final int requestCode) {
		String lettertype = "txt";
		String fbody = null, fsize = null, fext = null;
		if (!TextUtils.isEmpty(picPathString)) {
			lettertype = "img";
			fbody = PictureUtil.getPicString(picPathString, 512);
			fext = picPathString.substring(picPathString.lastIndexOf(".") + 1);
			fsize = fbody.length() + "";
		} else if (!TextUtils.isEmpty(contentString)) {
			lettertype = "txt";
		}

		NetworkClient.getNetworkClient().PostRequest(
				new SendPrivateLetterRequest(mParentContext, lettertype, fbody,
						(System.currentTimeMillis() / 1000) + "", fsize, fext,
						contentString), new SendPrivateLetterResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						DebugLog.logI("picPathString : " + picPathString);
						if (requestCode == UploadPic.PHOTO_PICKED_WITH_DATA) {
							mUploadPic.removePicture(picPathString);
						}

						String errorString = getString(R.string.failed_to_send);

						if ("1".equals(code)) {
							// HandlerToastUI.getHandlerToastUI(mParentContext,
							// "发送成功");
							HandlerPostUI.getHandlerPostUI(new Runnable() {

								@Override
								public void run() {
									mContentEditText.setText("");
								}
							});
							getPrivateLetterList(false);
						} else if ("-2".equals(code)) {
							// ftext不能为空当lettertype为img时
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else if ("-3".equals(code)) {
							// content不能为空当lettertype为txt时
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else if ("-4".equals(code)) {
							// 系统错误数据插入数据库失败
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else if ("-5".equals(code)) {
							// 当上传图片时fbodyftimefextfsize为空
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else if ("-6".equals(code)) {
							// 图片不是base64
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else if ("-7".equals(code)) {
							// 文件大小和得到的文件大小不同
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						} else {
							HandlerToastUI.getHandlerToastUI(mParentContext,
									errorString);
						}
					}
				}, null, new IErrorListener() {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						if (mParentContext instanceof Activity) {
							StringBuffer stringBuffer = new StringBuffer();
							ErrorExceptionHandler.NetworkExceptionHandler(
									stringBuffer, error);
							if (!TextUtils.isEmpty(stringBuffer.toString())) {
								HandlerToastUI.getHandlerToastUI(
										mParentContext, stringBuffer.toString());
							}
						}
						mUploadPic.removePicture(picPathString);
					}
				});
	}

	private void getPrivateLetterList(final boolean moreFlag) {
		if (!moreFlag) {
			mLastStartTime = "0";
		}
		NetworkClient.getNetworkClient().GetRequest(
				new GetPrivateLetterListRequest(mParentContext, mLastStartTime,
						"0"), new GetPrivateLetterListResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {

						final List<Letter> tempLetterList = new ArrayList<Letter>();
						if (moreFlag) {
							// 更多
							if (0 != letterList.size()) {
								String listAddTime = "-1";
								tempLetterList.addAll(mLetterList);
								tempLetterList.addAll(0, letterList);
								for (int i = 0; i < tempLetterList.size(); i++) {
									String date = tempLetterList.get(i).showDate;
									if ("-1".equals(listAddTime)
											|| !date.equals(listAddTime)) {
										tempLetterList.get(i).isShowDate = true;
										listAddTime = date;
									} else {
										tempLetterList.get(i).isShowDate = false;
									}
								}
							} else {
								HandlerToastUI
										.getHandlerToastUI(
												mParentContext,
												getString(R.string.no_more_information));
							}
						}

						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								if ("1".equals(code)) {
									if (0 != letterList.size()) {
										mLastStartTime = letterList.get(0).addtime;
									}
									mInformationAdapter.clearLastAddTime();
									if (moreFlag) {
										// 更多
										if (0 != letterList.size()) {
											mLetterList.clear();
											mLetterList.addAll(tempLetterList);
											// mLetterList.addAll(0,
											// letterList);
											mInformationAdapter
													.notifyDataSetChanged();
										} else {
											HandlerToastUI
													.getHandlerToastUI(
															mParentContext,
															getString(R.string.no_more_information));
										}
									} else {
										// 刷新
										mLetterList.clear();
										mLetterList.addAll(0, letterList);
										mInformationAdapter
												.notifyDataSetChanged();
										mPullToRefreshListView
												.getRefreshableView()
												.setSelection(
														mInformationAdapter
																.getCount() - 1);
										
										if(0 == mLetterList.size()){
											mNoDataLayout.setVisibility(View.VISIBLE);
											mPullToRefreshListView.setVisibility(View.GONE);
										}else {
											mNoDataLayout.setVisibility(View.GONE);
											mPullToRefreshListView.setVisibility(View.VISIBLE);
										}
										
									}

								} else if ("-4".equals(code)) {
									// HandlerToastUI.getHandlerToastUI(
									// mParentContext, "不是老师操纵");
								}
							}
						});

					}
				});
	}

	@Override
	protected void setTitleNavBar(View view) {
		TitleNavBarView titleNavBarView = (TitleNavBarView) view
				.findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(getString(R.string.message));
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
//				InputMethodUtils.softKeyboard(mApplication);
				InputMethodUtils.hideSoftKeyboard(mParentContext, mContentEditText);
				((SlidingActivity) mParentContext).toggle();
			}
		});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	@Override
	protected void setListener(View view) {
		mContentEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });

		mUploadPic.setOnGetPicSucceed(new OnGetPicSucceed() {

			@Override
			public void onGetPicSucceed(String picPathString, int requestCode) {
				DebugLog.logI("picPathString : " + picPathString);
				sendPrivateLetter(picPathString, null, requestCode);
			}
		});

		ImageView pictureImageView = (ImageView) view
				.findViewById(R.id.pictureImageView);
		pictureImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mUploadPic.doPickPhotoAction();
			}
		});
		Button sendButton = (Button) view.findViewById(R.id.sendButton);
		sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(mContentEditText.getText().toString())) {
					// HandlerToastUI.getHandlerToastUI(mParentContext,
					// "请填写问题");
				} else {
					sendPrivateLetter(null, mContentEditText.getText()
							.toString(),-1);
				}
			}
		});
		mPullToRefreshListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								getPrivateLetterList(true);
								DebugLog.logI("onRefresh");
								mPullToRefreshListView.onRefreshComplete();

							}
						});
					}
				});
		mInformationAdapter.setImageOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String contentString = (String) arg0.getTag();
				DebugLog.logI("image contentString : " + contentString);
				Intent intent = new Intent(mParentContext,
						BigPictureActivity.class);
				Picture picture = new Picture();
				picture.setPicturePath(contentString);
				List<Picture> list = new ArrayList<Picture>();
				list.add(picture);
				intent.putExtra("pictureList", (ArrayList<Picture>) list);
				startActivity(intent);
			}
		});
		mInformationAdapter.setTextOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String contentString = (String) arg0.getTag();
				DebugLog.logI("text contentString : " + contentString);
				copyContentDialog(contentString, arg0);
			}
		});
	}

	private void copyContentDialog(final String contentString, final View anchor) {
		final CustomPopupWindow customPopupWindow = new CustomPopupWindow(
				mParentContext);
		View view = LayoutInflater.from(mParentContext).inflate(
				R.layout.popup_letter_content_copy, null);
		ViewGroup copyLayout = (ViewGroup) view.findViewById(R.id.copyLayout);
		copyLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ClipboardUtils.copy(contentString, mParentContext);
				customPopupWindow.dismiss();
			}
		});
		int width = ToolUtils.dipToPx(mParentContext, 50);
		int height = ToolUtils.dipToPx(mParentContext, 50);
		customPopupWindow.setContentView(view, width, height);
		customPopupWindow.show(anchor, anchor.getWidth() / 2 - width / 2,
				-anchor.getHeight() - height);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != mUploadPic) {
			mUploadPic.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	/**
	 * 判断网络连接监听
	 */
	private BroadcastReceiver mNetConnectBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
				UploadFileUtils.getUploadUtils().setContext(mParentContext);
				UploadFileUtils.getUploadUtils().setFragment(mFragment);
				UploadFileUtils.getUploadUtils().uploadFileService();
			}
		}
	};

	private BroadcastReceiver mUpdateUiBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			DebugLog.logI("mUpdateUiBroadcastReceiver InformationFragment");
			if (UPDATE_INFOR_LIST.equals(intent.getAction())) {
				// 点击推送消息的时候更新列表
				getPrivateLetterList(false);
			} else if (HomeMenuFragment.UPDATE_INFOR_COUNT.equals(intent
					.getAction())) {
				// 点击推送消息的时候更新列表
				getPrivateLetterList(false);
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		// 注册广播
		
		IntentFilter netConnectIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
		mParentContext.registerReceiver(mNetConnectBroadcastReceiver, netConnectIntentFilter);
		
		IntentFilter intentFilter = new IntentFilter(UPDATE_INFOR_LIST);
		intentFilter.addAction(HomeMenuFragment.UPDATE_INFOR_COUNT);
		mParentContext.registerReceiver(mUpdateUiBroadcastReceiver,
				intentFilter);
		DebugLog.logI("InformationFragment onResume");
	}

	@Override
	public void onPause() {
		super.onPause();
		
		mParentContext.unregisterReceiver(mUpdateUiBroadcastReceiver);
		
		mParentContext.unregisterReceiver(mNetConnectBroadcastReceiver);
		
		DebugLog.logI("InformationFragment onPause");
	}

}
